<template>
  <Authority :value="auth">
    <a-popconfirm title="确定要删除吗？" ok-text="是" cancel-text="否" @confirm.stop="handleRemove">
      <a-button
        :type="small ? 'link' : 'primary'"
        :size="small ? 'small' : 'middle'"
        danger
        :loading="loading"
      >
        <template #icon>
          <Icon icon="lucide:trash-2" />
        </template>
        {{ text }}
      </a-button>
    </a-popconfirm>
  </Authority>
</template>

<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { Icon } from '@/components/Icon';
  import { propTypes } from '@/utils/propTypes';
  import { Authority } from '@/components/Authority';
  import { isFunction } from '@/utils/is';

  export default defineComponent({
    name: 'AButtonRemove',
    components: { Authority, Icon },
    props: {
      auth: propTypes.string,
      small: propTypes.bool,
      id: propTypes.string,
      text: propTypes.string.def('删除'),
      // 删除api
      api: { type: Function as PropType<(id: string) => Promise<boolean>> },
    },
    emits: ['success', 'fail'],
    setup(props, { emit }) {
      const loading = ref(false);

      const handleRemove = async () => {
        const { api } = props;
        if (!api || !isFunction(api)) return;

        loading.value = true;
        let result;
        try {
          result = await api(props.id);
        } catch (e) {
          console.error(e);
        } finally {
          loading.value = false;
        }
        if (result) {
          emit('success', props.id);
        } else {
          emit('fail', props.id);
        }
      };

      return {
        loading,
        handleRemove,
      };
    },
  });
</script>
